/* eslint-disable no-restricted-syntax */
import Vue from 'vue';
import axios from 'axios';

const downloadFile = (data, fileName, type) => {
  if (!data) {
    return;
  }
  let fileType = '';
  switch (type) {
    case 'pdf':
      fileType = 'application/pdf';
      break;
    default:
    case 'xls':
      fileType = 'application/vnd.ms-excel';
      break;
  }
  const blob = new Blob([data], { type: fileType });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', fileName);
  document.body.appendChild(link);
  link.click();
};

const putFile = (url, options, fileName = 'file', cb, type = 'xls') => {
  axios({
    method: 'post',
    url,
    headers: { sessionId: sessionStorage.getItem('sessionId'), 'Content-type': 'application/json;charset=UTF-8' },
    responseType: 'blob',
    data: { ...options },
  }).then((res) => {
    // console.log(type);
    downloadFile(res, `${fileName}.${type}`, type);
    cb();
  });
};


Vue.prototype.$excel = putFile;


export default putFile;
